﻿using BlockMain_Class;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace RaftFSM
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {

        public static ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("127.0.0.1:6379");
        private TextBox tb;
        //委托 线程委托修改ui
        public delegate void UpdateTextCallback(string message);
        public MainWindow()
        {
            InitializeComponent();
            this.tb = text;
            WindowStartupLocation = WindowStartupLocation.CenterScreen;
            this.Topmost = true;
        }

        /// <summary>
        /// 开始工作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //监听任务队列
            ISubscriber sub = redis.GetSubscriber();
            //1)处理peer队列
            sub.Subscribe("peer", (channel, message) =>
            {
                //输出收到的消息
                AddTest($"[{DateTime.Now:HH:mm:ss}] {message}");
                var data = message;
                //节点raft处理一致性
                Agreement(data);
            });
            //提示
            MessageBox.Show("已开始监听");
            this.start.Content = "正在监听...";
            this.start.IsEnabled = false;
        }

        /// <summary>
        /// 处理状态 逐条验证
        /// </summary>
        /// <param name="data"></param>
        public void Agreement(object data)
        {
            try
            {
                //rpc与节点客户端通讯验证 【重点】
                //1)GrPC
                //具体操作如下 
                //1）本服务为客户端 进行过程调用验证数据有效性【每个节点是服务端】
                //通知-Peer1【领袖节点】 后期环境要求下可更换Consul
                //Peer1广播给其他发现的节点 执行远程过程调用验证 
                //验证通过后入列【内存队列】
                //异步处理内存队列入库【DB】
                //以上想法推翻


                //获取领袖节点 

                var url = getbool("http://localhost:8500/v1/status/leader");
                if (url != null)
                {
                    var istrue = getbool("http://" + url + "/api/values?data=" + data.ToString());
                    if (istrue == "true")
                    {
                        //验证通过,传出统一的数据
                        Cache.Sub("copy", data.ToString());
                    }
                    else
                    {
                        AddTest("请求失败");
                        AddTest("请求失败"+ istrue);
                    }
                }

            }
            catch (Exception e)
            {
                AddTest("Agreement出错信息" + e.Message);
            }
        }


        public string getbool(string url)
        {
            var request = (HttpWebRequest)WebRequest.Create(url);
            var response = (HttpWebResponse)request.GetResponse();
            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
            return responseString;
        }

        /// <summary>
        /// 修改文本框内容
        /// </summary>
        /// <param name="message"></param>
        private void UpdateText(string message)
        {
            tb.AppendText(message + "\n");
            tb.ScrollToEnd();//滚动到光标处
        }

        //工作线程
        private void AddTest(string text)
        {
            //调用委托
            tb.Dispatcher.Invoke(
                new UpdateTextCallback(this.UpdateText), text
            );
        }


    }
}
